<template>
  <a-modal title="商品" :width="700" :visible="visible" @ok="submit" @cancel="cancelAdd">
    <a-form :form="form">
      <a-form-item label="图片">
        <!-- <a-upload class="swiperUpload" :action="aliOssConfig.uploadUrl" :data="formData" list-type="picture-card"
          v-decorator="['images', { rules: [{ required: true, message: '请上传轮播图！' }] }]" :file-list="fileList"
          :before-upload="beforeUpload" @preview="handlePreview" @change="handleChange">
          <div v-if="fileList.length < 8">
            <a-icon type="plus" />
            <div class="ant-upload-text">Upload</div>
          </div>
        </a-upload> -->
        <uploadBox ref='upload' @success='uploadSuccess'
          v-decorator="['images', { rules: [{ required: true, message: '请上传图片！' }] }]"></uploadBox>
      </a-form-item>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="所属分类">
            <a-select v-decorator="['goodtypeid', { rules: [{ required: true, message: '请选择' }] }]" placeholder="请选择！"
              :default-active-first-option="false" :show-arrow="false" :filter-option="false">
              <a-select-option v-for="(item, index) in goodstypeList" :key="item.id" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="名称">
            <a-input v-decorator="['name', { rules: [{ required: true, message: '请输入' }] }]" placeholder="" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="规格">
            <a-input v-decorator="['guige', { rules: [{ required: true, message: '请输入' }] }]" placeholder="" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="单位">
            <a-input v-decorator="['danwei', { rules: [{ required: true, message: '请输入' }] }]" placeholder="" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="厂家">
            <a-input v-decorator="['changjia', { rules: [{ required: true, message: '请输入' }] }]" placeholder="" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="价格">
            <a-input v-decorator="['price', { rules: [{ required: true, message: '请输入' }] }]" placeholder="" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="医生指数">
            <a-input v-decorator="['zhishuo', { rules: [{ required: true, message: '请输入' }] }]" placeholder="" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script>
  import {
    typeList,
    goodsAdd,
    goodsUpdate
  } from '@/api/goods'
  import {
    getFormData
  } from '@/utils/aliOss/aliossUpload.js'
  import aliOssConfig from '@/utils/aliOss/config'
  import uploadBox from '@/components/obsUpload/obsUploadList'

  const formItemLayout = {
    labelCol: {
      span: 4
    },
    wrapperCol: {
      span: 8
    },
  };
  const formTailLayout = {
    labelCol: {
      span: 4
    },
    wrapperCol: {
      span: 8,
      offset: 4
    },
  };

  export default {
    components: {
      uploadBox
    },
    props: {
      visible: {
        type: Boolean,
        required: true,
      }
    },
    data() {
      return {
        fileList: [],
        checkNick: false,
        formItemLayout,
        formTailLayout,
        form: this.$form.createForm(this),
        loading: false,
        imageUrl: '',
        formData: {},
        aliOssConfig: aliOssConfig,
        id: 0,
        updateflag: false,
        goodstypeList: []
      };
    },
    created() {
      this.getTypeList()
    },
    methods: {
      uploadSuccess(v) {
        this.fileList = v
        let values = this.form.getFieldsValue();
        values.images = v
        this.form.setFieldsValue(values);
      },
      getTypeList() {
        typeList().then(res => {
          this.goodstypeList = res.data
        })
      },
      cancelAdd() {
        this.updateflag = false
        this.$emit('cancel', true)
        this.form.resetFields()
        this.fileList = []
        this.$refs.upload.fileList = []
      },
      setUpdate(formValue) {
        var that = this
        var imagesArray = []
        imagesArray = formValue.images.split(',')
        var imagesNewArray = []
        for (var i = 0; i < imagesArray.length; i++) {
          imagesNewArray.push({
            url: imagesArray[i],
            name: new Date().getTime() + '.png',
            status: 'done',
            uid: (((1 + Math.random()) * 0x10000) | 0).toString(16),
          })
        }

        that.fileList = imagesNewArray
        this.$refs.upload.fileList = imagesNewArray
        
        this.updateflag = true
        this.id = formValue.id
        that.form.setFieldsValue({
          name: formValue.name,
          goodtypeid: formValue.goodtypeid,
          images: formValue.images,
          guige: formValue.guige,
          danwei: formValue.danwei,
          changjia: formValue.changjia,
          price: formValue.price,
          zhishuo: formValue.zhishuo
        })
      },
      submit() {
        var that = this
        const {
          form: {
            validateFields
          },
        } = this

        validateFields((errors, values) => {
          if (!errors) {
            var swiperImageArray = []
            for (var i = 0; i < this.fileList.length; i++) {
              swiperImageArray.push(that.fileList[i].url);
            }
            values.images = swiperImageArray.join(',');
            values.price = values.price * 1
            values.zhishuo = values.zhishuo * 1
            if (this.updateflag) {
              values.id = this.id
              goodsUpdate({
                ...values,
              }).then((res) => {
                if (res.code == 0) {
                  that.form.resetFields()
                  that.fileList = []
                  this.$refs.upload.fileList = []
                  that.$emit('ok')
                }
              })
            } else {
              goodsAdd({
                ...values,
              }).then((res) => {
                if (res.code == 0) {
                  that.form.resetFields()
                  that.fileList = []
                  this.$refs.upload.fileList = []
                  that.$emit('ok')
                }
              })
            }
          }
        })
      },
      check() {
        this.form.validateFields(err => {
          if (!err) {
            console.info('success');
          }
        });
      },
      async handlePreview(file) {
        if (!file.url && !file.preview) {
          file.preview = await getBase64(file.originFileObj)
        }
        this.previewImage = file.url || file.preview
        this.previewVisible = true
      },
      beforeUpload(file) {
        this.formData = getFormData()
      },
      handleChange(info) {
        var that = this;
        const isJpgOrPng = info.file.type === 'image/jpeg' || info.file.type === 'image/png'

        if (!isJpgOrPng) {
          this.$message.error('您只能上传图片类型文件!')
          return
        }

        const isLt2M = info.file.size / 1024 / 1024 < 1

        if (!isLt2M) {
          this.$message.error('图片必须小于 1MB!')
          return
        }

        if (info.file.status == "done") {
          info.fileList[info.fileList.length - 1].url = that.aliOssConfig.uploadUrl + '/' + that.formData.key;
        }

        this.fileList = info.fileList

        setTimeout(() => {
          //上传图片后 给缩略图表单项赋值
          that.form.setFieldsValue({
            bannerCurrrent: 0
          });
        }, 200);

      },
    },
  };
</script>